package com.daykw.xiaohongshu.task;

import java.util.List;

import org.apache.log4j.Logger;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.stereotype.Service;

import com.daykw.xiaohongshu.model.TArticleTask;
import com.daykw.xiaohongshu.mq.TQueue;
import com.daykw.xiaohongshu.util.Const;
import com.daykw.xiaohongshu.util.SpringContextHolder;
import com.daykw.xiaohongshu.util.ZKC;

@DisallowConcurrentExecution
@Service
public class ArticleJob implements Runnable {

	private static Logger logger = Logger.getLogger(ArticleJob.class);

	@Override
	public void run() {

		NutDao dao = SpringContextHolder.getBean("dao");
		int LEN = 500;
		try {

			if (TQueue.getAQueue().size() > LEN) {
				logger.info("超过" + TQueue.getAQueue().size() + "************");
				return;
			}
			int total =  Const.ARTICLE_THREAD + (Const.ARTICLE_THREAD / 2);

//			String querySql = "SELECT * FROM 	t_article_task WHERE	id >= (	(SELECT MAX(id) FROM t_article_task  where  STATUS = 0) - (SELECT MIN(id) FROM t_article_task  where  STATUS = 0)	) * RAND() + (SELECT MIN(id) FROM t_article_task) and status=0 LIMIT  "
//					+ total;
			
			
			long t1 = System.currentTimeMillis();
		
			

			String node = Const.getLocalHostIp();
//			int size  = ZKC.getZKClient().getChildren().size();
//			int index = ZKC.getZKClient().getNodeIndex(node);
			int size = 100;
			java.util.Random random = new java.util.Random();
			int r = random.nextInt(size);
			
			String querySql = "SELECT * FROM t_article_task where status = 0 and mod(id,"+size+")="+r+" LIMIT "+total;

			Sql sql = Sqls.queryEntity(querySql);
			sql.setCallback(Sqls.callback.entities());
			sql.setEntity(dao.getEntity(TArticleTask.class));
			dao.execute(sql);
			List<TArticleTask> list = sql.getList(TArticleTask.class);
			long t2 = System.currentTimeMillis();
			logger.info("节点:"+node+"查询文章耗时:" + (t2 - t1) + " ms,节点总数:"+size);
			for (TArticleTask task : list) {
				TQueue.getAQueue().add(task);
				
			}
			logger.info("增加************" + list.size() + "************");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

}
